package com.becca.cake.service.fixing.impl;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.becca.cake.core.exception.ServiceException;
import com.becca.cake.core.qiniu.FileNameRuleHelp;
import com.becca.cake.core.qiniu.QiNiuGoodsPicTemplate;
import com.becca.cake.core.qiniu.bean.QiNiuResponse;
import com.becca.cake.dao.fixing.FixingDAO;
import com.becca.cake.model.goods.GoodsFixingModel;
import com.becca.cake.model.system.AdminDO;
import com.becca.cake.service.fixing.IFixingService;
import com.becca.cake.util.CodeUtil;

/**
 * 配件管理service实现类
 * @copyright  尊星(上海)信息科技有限公司
 * @author yellow
 * @date 2016年6月13日 下午8:13:24
 */
@Service
public class FixingServiceImpl implements IFixingService {
    @Autowired
    private FixingDAO fixingDAO;

    @Override
    public List<GoodsFixingModel> queryFixings(Map<String, Object> map) throws ServiceException {
        return this.fixingDAO.queryFixings(map);
    }

    @Override
    public Long selectFixingCount(Map<String, Object> map) throws ServiceException {
        return this.fixingDAO.selectFixingCount(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertOrUpdateFixing(GoodsFixingModel goodsFixingModel, MultipartFile files,
                                     String fileTempPath, AdminDO adminDo) throws Exception {
        // 2.step 校验
        GoodsFixingModel.validInsertOrUpdateFixing(goodsFixingModel, files);
        // 3.step 上传图片
        String fixingPicPath = "";
        if (!files.isEmpty()) {
            //step3:重新生成图片文件名
            String fileName = FileNameRuleHelp.getGoodsPictureFileName() + "."
                              + FilenameUtils.getExtension(files.getOriginalFilename());
            String filePath = fileTempPath + File.separator + fileName;
            File localFile = new File(filePath);
            files.transferTo(localFile);
            //step4:调用七牛上传图片
            QiNiuResponse response = QiNiuGoodsPicTemplate.uploadFile(localFile, fileName);
            if (response.isSuccess()) {
                fixingPicPath = QiNiuGoodsPicTemplate.getDownloadUrl(response.key);
            } else {
                throw new ServiceException("图片上传失败!");
            }
            // step5:删除本地图片
            localFile.delete();
        }
        if (StringUtils.isNotEmpty(fixingPicPath)) {
            goodsFixingModel.setFixingPicture(fixingPicPath);
        }

        if (goodsFixingModel.getFixingPrice() == null) {
            goodsFixingModel.setFixingPrice(0.00);
        }

        if (goodsFixingModel.getId() == null) {//新增
            goodsFixingModel.setCreatedName(adminDo.getTrueName());
            goodsFixingModel.setIsEnable(GoodsFixingModel.IS_ENABLE);
            this.fixingDAO.insertFixing(goodsFixingModel);
            Map<String, Object> map = new HashMap<String, Object>();
            Integer fixingId = goodsFixingModel.getId();
            String fixingCode = CodeUtil.formatFixingCode("PG", fixingId);
            map.put("fixingId", fixingId);
            map.put("fixingCode", fixingCode);
            this.fixingDAO.updFixingCode(map);
        } else {//修改
            goodsFixingModel.setUpdatedName(adminDo.getTrueName());
            this.fixingDAO.updateFixing(goodsFixingModel);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateIsEnableById(Integer fixingId, Integer isEnable, String trueName)
                                                                                       throws ServiceException {
        // Integer fixingId = Integer.valueOf(map.get("fixingId").toString());
        GoodsFixingModel.validfixingIdIsNull(fixingId);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("fixingId", fixingId);
        paramMap.put("isEnable", isEnable);
        paramMap.put("userName", trueName);
        Long isEnableExist = this.fixingDAO.IsEnableExist(paramMap);
        if (isEnableExist != 0) {
            if ("0".equals(isEnable)) {
                throw new ServiceException(GoodsFixingModel.FIXING_IS_ENABLE_USER);
            } else {
                throw new ServiceException(GoodsFixingModel.FIXING_IS_ENABLE_FORBIDDEN);
            }
        }
        this.fixingDAO.updEnableOrOptionById(paramMap);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updateIsOptionalById(Integer fixingId, Integer isOptional, String trueName)
                                                                                           throws ServiceException {
        GoodsFixingModel.validfixingIdIsNull(fixingId);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("fixingId", fixingId);
        paramMap.put("isOptional", isOptional);
        paramMap.put("userName", trueName);
        Long isOptionalExist = this.fixingDAO.IsOptionalExist(paramMap);
        if (isOptionalExist != 0) {
            if ("0".equals(isOptional)) {
                throw new ServiceException(GoodsFixingModel.FIXING_ENABLE_EXIST);
            } else {
                throw new ServiceException(GoodsFixingModel.FIXING_NOT_ENABLE_EXIST);
            }
        }
        this.fixingDAO.updEnableOrOptionById(paramMap);
    }

    @Override
    public GoodsFixingModel selectFixingById(Integer fixingId) throws ServiceException {
        return this.fixingDAO.selectFixingById(fixingId);
    }

}
